package com.yanggu.jt808.model.resp;

import com.yanggu.jt808.model.base.DataPackage;
import com.yanggu.jt808.model.base.Header;
import com.yanggu.jt808.consts.Jt808Constant;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import lombok.Data;
import org.springframework.beans.BeanUtils;

/**
 * @author: bo
 * @Description: 平台通用应答
 * @Version: 1.0
 */
@Data
public class CommonResp extends DataPackage {
    public static final byte SUCCESS = 0;//成功/确认
    public static final byte FAILURE = 1;//失败
    public static final byte MSG_ERROR = 2;//消息有误
    public static final byte UNSUPPORTED = 3;//不支持
    public static final byte ALARM_PROCESS_ACK = 4;//报警处理确认

    private int replyFlowId; //应答流水号 2字节
    private short replyId; //应答 ID  2字节
    private byte result;    //结果 1字节


    public CommonResp() {
        this.getHeader().setMsgId(Jt808Constant.平台通用应答);
    }

    @Override
    public ByteBuf toByteBufMsg() {
        ByteBuf bb = super.toByteBufMsg();
        bb.writeShort(replyFlowId);
        bb.writeShort(replyId);
        bb.writeByte(result);
        return bb;
    }

    public static CommonResp response(DataPackage msg, int flowId, byte result) {
        if (result != SUCCESS && result != FAILURE && result != MSG_ERROR && result != UNSUPPORTED && result != ALARM_PROCESS_ACK) {
            throw new RuntimeException("传入的result有误");
        }
        CommonResp resp = new CommonResp();

        //设置一些参数
        resp.copyBy(msg,flowId);
        //应答流水号
        resp.setReplyFlowId(msg.getHeader().getFlowId());


        //封装返回的信息
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.heapBuffer(5);
        //应答流水号(2个字节)对应的终端消息的流水号
        byteBuf.writeShort(resp.getHeader().getFlowId());
        //应答ID(2个字节)对应的终端消息的ID
        byteBuf.writeShort(resp.getHeader().getMsgId());
        byteBuf.writeByte(result);
        //设置返回的消息
        resp.setMsgBody(byteBuf);
        return resp;
    }

}
